import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";
import { useCachedViewStoreHook } from "@/store/modules/cachedView";
import { WHITE_LIST, REDIRECT_PATH, BASE_URL } from '@/config/setting';
import { getToken } from '@/utils/token-util';
import NProgress from "@/utils/progress";
import setPageTitle from "@/utils/set-page-title";

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  // 路由缓存
  useCachedViewStoreHook().addCachedView(to);
  // 页面 title
  setPageTitle(to.meta.title);
  next();
});


/**
 * 路由守卫
 */
router.beforeEach(async (to, from) => {
  // 网站顶部小进度条开启
  if (!from.path.includes(REDIRECT_PATH)) {
    NProgress.start();
  }

  // 当前用户没有登录，没有token
  if (!getToken()) {
    // 当前路径不存在白名单内
    if (!WHITE_LIST.includes(to.path)) {
      // 当前路径不在白名单，如果开启了sso，并且未携带有errorCode（单点返回来的），跳转到单点detection
      return {
        path: '/login',
        query: to.path === '/' ? {} : { from: to.path }
      };
    }
  }

  // 可以获取到token，代表用户已经登录了
  else {
    // 校验系统是否初始化过，如果没有初始化过，则进入初始化界面初始化一些后台需要的参数
  }
});

router.afterEach(to => {
  if (!to.path.includes(REDIRECT_PATH) && NProgress.isStarted()) {
    setTimeout(() => {
      NProgress.done(true);
    }, 200);
  }
});
export default router;
